package com.jyx.malls.service.impl;

import com.jyx.malls.dao.UserMapper;
import com.jyx.malls.pojo.User;
import com.jyx.malls.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @auther 姜永新
 * @create 2020-07-21-8:41
 */
@Service
public class UserServiceImpl implements IUserService {
   @Autowired
    private UserMapper userMapper;

    /**
     * 注册功能
     * @param user
     */
    @Override
    public void register(User user) {
        //用户名不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if(countByUsername>0){
            throw new RuntimeException("该用户名已经被注册");
        }
        //邮箱不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if(countByEmail>0){
            throw new RuntimeException("该邮箱已经被注册");
        }
        //MD5摘要算法
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount==0){
            throw new RuntimeException("注册失败");
        }
    }
}
